package com.example.nutritionmanager.profile

import android.app.Activity
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.nutritionmanager.UserProfile
import com.example.nutritionmanager.viewModels.UserProfileState
import com.example.nutritionmanager.viewModels.UserProfileViewModel
import com.example.nutritionmanager.buttons.PrimaryButton
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProfileInfoScreen(viewModel: UserProfileViewModel = hiltViewModel()) {
    val userProfileState by viewModel.userProfileState.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }
    val scope = rememberCoroutineScope()

    // 输入状态
    var editableProfile by remember { mutableStateOf(UserProfile("1","1","1","1","1","1","1","1")) }
    val context = LocalContext.current
    val activity = remember { context as? Activity }

    LaunchedEffect(userProfileState) {
        when (val state = userProfileState) {
            is UserProfileState.Success -> {
                editableProfile = state.userProfile.copy(
                    // 转换显示格式
                    gender = when(state.userProfile.gender) {
                        "男" -> "1"
                        "女" -> "2"
                        else -> "0"
                    },
                    period = when(state.userProfile.period) {
                        "减脂期" -> "1"
                        "增肌期" -> "2"
                        "保持期" -> "0"
                        else -> "3"
                    }
                )
            }
            is UserProfileState.Error -> {
                scope.launch { snackbarHostState.showSnackbar(state.error) }
            }
            else -> {}
        }
    }

    Scaffold(
        snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
        topBar = {
            TopAppBar(
                title = { Text("我的资料", color = MaterialTheme.colorScheme.onPrimary) },
                navigationIcon = {
                    IconButton(onClick = { activity?.finish() }) {
                        Icon(
                            imageVector = Icons.Filled.ArrowBack,
                            contentDescription = "返回",
                            tint = Color.White
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary
                )
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background)
                .padding(padding)
                .verticalScroll(rememberScrollState())
        ) {
            // 基础信息卡片
            ProfileEditCard(title = "基本信息") {
                ProfileInputField(
                    label = "用户名",
                    value = editableProfile.username,
                    onValueChange = { editableProfile = editableProfile.copy(username = it) }
                )

                GenderSelector(
                    selected = editableProfile.gender,
                    onSelect = { editableProfile = editableProfile.copy(gender = it) }
                )

                ProfileInputField(
                    label = "年龄",
                    value = editableProfile.age,
                    onValueChange = { editableProfile = editableProfile.copy(age = it) },
                )
            }

            // 身体数据卡片
            ProfileEditCard(title = "身体数据") {
                ProfileInputField(
                    label = "身高 (cm)",
                    value = editableProfile.height,
                    onValueChange = { editableProfile = editableProfile.copy(height = it) }
                )

                ProfileInputField(
                    label = "体重 (kg)",
                    value = editableProfile.weight,
                    onValueChange = { editableProfile = editableProfile.copy(weight = it) }
                )
            }

            // 健身目标卡片
            ProfileEditCard(title = "健身目标") {
                PeriodSelector(
                    selected = editableProfile.period,
                    onSelect = { editableProfile = editableProfile.copy(period = it) }
                )

                ProfileInputField(
                    label = "目标热量 (kcal)",
                    value = editableProfile.targetCalories,
                    onValueChange = { editableProfile = editableProfile.copy(targetCalories = it) }
                )
            }

            Spacer(Modifier.height(24.dp))

            PrimaryButton(
                onClick = {
                    viewModel.updateUserProfile(
                        UserProfile(
                            username = editableProfile.username,
                            gender = editableProfile.gender,
                            age = editableProfile.age,
                            height = editableProfile.height,
                            weight = editableProfile.weight,
                            period = editableProfile.period,
                            targetCalories = editableProfile.targetCalories,
                            registerDate = editableProfile.registerDate
                        )
                    )
                    activity?.finish()
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp)
                    .padding(bottom = 24.dp),
                text = "保存修改"
            )
        }
    }
}

// 可复用组件
@Composable
private fun ProfileEditCard(title: String, content: @Composable ColumnScope.() -> Unit) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp)
            .padding(top = 16.dp),
        shape = RoundedCornerShape(16.dp),
        elevation = CardDefaults.cardElevation(4.dp),
        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text(
                text = title,
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.primary,
                modifier = Modifier.padding(bottom = 12.dp)
            )
            content()
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun GenderSelector(selected: String, onSelect: (String) -> Unit) {
    val options = listOf("1" to "男", "2" to "女", "0" to "保密")
    val expanded = remember { mutableStateOf(false) }
    Text(text = "性别", fontSize = 14.sp, color = MaterialTheme.colorScheme.onSurface)
    ExposedDropdownMenuBox(
        modifier = Modifier.fillMaxWidth(),
        expanded = expanded.value, // 传递Boolean值而不是状态对象
        onExpandedChange = { expanded.value = it }
    ) {
        TextField(
            value = options.find { it.first == selected }?.second ?: "",
            onValueChange = {},
            readOnly = true,
            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded.value) },
            colors = TextFieldDefaults.colors(
                unfocusedContainerColor = Color.Transparent,
                focusedContainerColor = Color.Transparent
            ),
            modifier = Modifier.menuAnchor().padding(vertical = 12.dp).padding(start = 12.dp).border(width = 1.dp, color = Color.Gray)
        )

        ExposedDropdownMenu(
            expanded = expanded.value,
            onDismissRequest = { expanded.value = false }, 
            modifier = Modifier.padding(horizontal = 6.dp).background(Color.LightGray)
        ) {
            options.forEach { (value, label) ->
                DropdownMenuItem(
                    text = { Text(label) },
                    onClick = {
                        onSelect(value)
                        expanded.value = false
                    }
                )
            }
        }
    }
}


@Composable
private fun PeriodSelector(selected: String, onSelect: (String) -> Unit) {
    val options = listOf("1" to "减脂期", "2" to "增肌期", "0" to "保持期")

    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        options.forEach { (value, label) ->
            FilterChip(
                selected = selected == value,
                onClick = { onSelect(value) },
                label = { Text(label) },
                modifier = Modifier.weight(1f),
                colors = FilterChipDefaults.filterChipColors(
                    containerColor = MaterialTheme.colorScheme.surface,
                    selectedContainerColor = MaterialTheme.colorScheme.primary,
                    selectedLabelColor = MaterialTheme.colorScheme.onPrimary,
                    labelColor = MaterialTheme.colorScheme.onSurface
                )
            )
            if (value != options.last().first) Spacer(Modifier.width(8.dp))
        }
    }
}

@Preview
@Composable
fun GenderSelectorPreview() {
    GenderSelector(selected = "1", onSelect = {})
}